package com.ahui.mallchat.common.user.service.adapter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ahui.mallchat.common.common.enums.YesOrNoEnum;
import com.ahui.mallchat.common.user.domain.entity.ItemConfig;
import com.ahui.mallchat.common.user.domain.entity.User;
import com.ahui.mallchat.common.user.domain.entity.UserBackpack;
import com.ahui.mallchat.common.user.domain.vo.resp.BadgeResp;
import com.ahui.mallchat.common.user.domain.vo.resp.UserInfoResp;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Author:ahui
 * Description:
 * Date: 2024/7/21 13:18
 */
public class UserAdapter {
    public static User buildUserSave(String openId) {
        return User.builder().openId(openId).build();
    }

    public static User buildAuthorizeUser(Long uid, WxOAuth2UserInfo userInfo) {
        User user = new User();
        user.setId(uid);
        user.setName(userInfo.getNickname());
        user.setAvatar(userInfo.getHeadImgUrl());
        return user;
    }

    public static UserInfoResp buildUserInfo(User user, Integer modifyNameCount) {
        UserInfoResp vo = new UserInfoResp();
        BeanUtil.copyProperties(user,vo);
        vo.setModifyNameChance(modifyNameCount);
        return vo;
    }

    public static List<BadgeResp> buildBadgeResp(List<ItemConfig> itemConfigs, List<UserBackpack> backpacks, User user) {
        if (ObjectUtil.isNull(user)) {
            // 这里 user 入参可能为空，防止 NPE 问题
            return Collections.emptyList();
        }
        Set<Long> obtainItemSet = backpacks.stream().map(UserBackpack::getItemId).collect(Collectors.toSet());
        return itemConfigs.stream().map(a -> {
            BadgeResp resp = new BadgeResp();
            BeanUtil.copyProperties(a,resp);
            resp.setObtain(obtainItemSet.contains(a.getId())? YesOrNoEnum.Yes.getStatus() : YesOrNoEnum.No.getStatus());
            resp.setWearing(Objects.equals(a.getId(),user.getItemId()) ? YesOrNoEnum.Yes.getStatus() : YesOrNoEnum.No.getStatus());
            return resp;
        }).sorted(Comparator.comparing(BadgeResp::getWearing,Comparator.reverseOrder())
                .thenComparing(BadgeResp::getObtain,Comparator.reverseOrder()))
                .collect(Collectors.toList());
    }
}
